<?php
	function plexGetSections(){
		global $config, $logger;
		
		$url = $config['plex_url'] . '/library/sections';
		$logger->info('Searching for sections in the Plex library at ' . $config['plex_url']);

		$xml = load_xml_from_url($url);
		if(!$xml) return false;

		$total_sections = intval($xml->attributes()->size);
		if($total_sections<=0) {
			$logger->error('No sections were found in this Plex library');
			return false;
		}

		$xml_sections = $xml->xpath('//Directory[@type="movie" or @type="show"]');
		$num_sections = count($xml_sections);
		//$num_sections = $xml->xpath('count(//Directory[@type="movie" or @type="show"])');
		
		$logger->info('Found ' . $num_sections . ' ' . inflect($num_sections, 'section') . ' in this Plex library');

		return $xml;
	}
	
	//*
	
	function plexGetMedia($key, $category = '', $filter = ''){
		global $config, $logger;
		$logger->info('Start=======================================plex Get Media function=======================================Start');
                $logger->info('Memory Usage: ' . memory_get_usage());		
                
		if(empty($category)) $category = $config['category'];
		
		if(empty($filter)){
			$url = $config['plex_url'] . '/library/sections/' . $key . '/' . $category;
			$logger->info('Searching for Media in the Plex library at ' . $url);
		} else {
			$url = $config['plex_url'] . '/library/sections/' . $key . '/' . $category . '/' . $filter;
			$logger->info('Searching for Media in the Plex library at ' . $url);
		}
                
                $logger->info('Getting Plex xml From: ' . $url);
		$xml = load_xml_from_url($url);
		if(!$xml) return false;

		$total_sections = intval($xml->attributes()->size);
		if($total_sections<=0) {
			$logger->error('No media was found in this Plex library');
                        $logger->info('Memory Usage: ' . memory_get_usage());
                        $logger->info('End=======================================plex Get Media function=======================================End');
			return false;
		}

		$numOfNodes = $xml['size'];
		
		$logger->info('Found ' . $numOfNodes . ' ' . inflect($numOfNodes, 'node') . ' in this Plex library');
                
                $logger->info('Memory Usage: ' . memory_get_usage());
                $logger->info('End=======================================plex Get Media function=======================================End');
		return $xml;
	}
        
        function plexGetMetadata($key){
            global $config, $logger;
				
		
                $url = $config['plex_url'] . $key;
                $logger->info('Getting Meta Data from ' . $url);


		$xml = load_xml_from_url($url);
		if(!$xml) return false;

		$total_sections = intval($xml->attributes()->size);
		if($total_sections<=0) {
			$logger->error('No media was found in this Plex library, url: ' . $url);
			return false;
		}

		return $xml;
        }
	
	function plexGetImage($url, $sizex, $sizey, $path = 'cache/') {
		global $config, $basePath, $logger;
                $logger->info('Start=======================================plex Get Image function=======================================Start');
		$path .= (substr($path, -1) == '/' ? '' : '/');
		$cache = $_SESSION['homePath'] . '/images/' . $path;
		
                
		$imgName = md5($url . $sizex . $sizey);
		$img = glob($cache . $imgName . '.*');
                $logger->info('plexGetImage Glob: ');
                $logger->info($img);
		if($img) return $img[0];
		
		$imgUrl = $config['plex_url'] . '/photo/:/transcode?width=' . $sizex . '&height=' . $sizey . '&url=' . urlencode($config['plex_url'] . $url);
                $logger->info('plexGetImage $imgUrl: ' . $imgUrl);
                $imgInfo = getimagesize($imgUrl);
                switch ($imgInfo['mime']){
                    case 'image/png':
                        $image = imagecreatefrompng($imgUrl);
                        imagealphablending($image, true);
                        imagesavealpha($image, true);
                        $saveImg = 'imagepng';
                        $ext = '.png';
                        break;
                    case 'image/jpeg':
                        $image = imagecreatefromjpeg($imgUrl);
                        $saveImg = 'imagejpeg';
                        $ext = '.jpg';
                        break;
                    default :
                        return $basePath . 'images/html/thumbDefault.jpg';
                        break;
                }
                $tempWidth = imagesx($image);
                $tempHight = imagesy($image);
                $logger->info('Image width: ' . $tempWidth . ' Image hight: ' .$tempHight);
                
                if($tempWidth < $sizex || $tempHight < $sizey) {
                    $new_image = imagecreatetruecolor($sizex, $sizey);
                    imagecopyresampled($new_image, $image, 0, 0, 0, 0, $sizex, $sizey, $tempWidth, $tempHight);
                    imagealphablending($new_image, true);
                    imagesavealpha($new_image, true);
                    $image = $new_image;
                }
		$saveImg($image, $cache . $imgName . $ext);
	
		imagedestroy($image);
                imagedestroy($new_image);
                $logger->info('End=======================================plex Get Image function=======================================End');
		return $cache . $imgName . $ext;
	}
	function inflect($num, $single) {
	
		if($num==1) return $single;
		
		return $single . 's';
	}
	
	function plexGetMovieFilters($section){
		global $config, $logger;
		
		$url = $config['plex_url'] . '/library/sections/' . $section;
		$logger->info('Searching for categories in the Plex library at ' . $url);

		$xml = load_xml_from_url($url);
		if(!$xml) return false;
		
		$arrayX = 0;
		foreach($xml->Directory as $category){
			$filtersUrl = $url . '/' . $category['key'];
			$filtersXml = load_xml_from_url($filtersUrl);
			if(!$filtersXml) continue;
			//$logger->info($filtersXml);
			if($filtersXml['viewGroup'] == 'secondary'){
				$filters[$arrayX][0] = $category['key'] .','. $category['title'];
				$arrayY = 1;
				foreach($filtersXml as $filter){
					$filters[$arrayX][$arrayY] = $filter['key'] .','. $filter['title'];
					$arrayY++;
				}
			$arrayX++;
			}
			if($filtersXml['viewGroup'] == 'movie'){
				$filters[$arrayX][0] = $category['key'] .','. $category['title'];
			}else{
				continue;
			}
			$arrayX++;
		}
		
		return $filters;
	}
	function plexSearch($query, $type = null){
		//http://192.168.0.3:32400/search?type=2&query=day%20of%20the
	}
?>